<template>
  <el-form ref="postFormRef" label-width="150px" class="ruleForm" :model="postForm" :rules="rules">
    <div class="form-title">基础信息</div>
    <el-form-item label="会场名称：" prop="name">
      <el-col :span="12">
        <el-input  v-model="postForm.name" maxlength="60" show-word-limit placeholder="请输入会场名称,不能超过60个字符" />
      </el-col>
    </el-form-item>
    <el-form-item label="会场短标题：" >
      <el-col :span="12">
        <el-input  v-model="postForm.tag" maxlength="60" show-word-limit placeholder="请输入会场短标题,不能超过60个字符" />
      </el-col>
    </el-form-item>
    <el-form-item label="会场类型：" prop="categoryId">
      <category v-model="postForm.categoryId" />
    </el-form-item>
    <el-form-item label="会场品牌：" prop="brandId">
      <brand v-model="postForm.brandId" />
    </el-form-item>
    <el-form-item label="地址：" prop="regionId">
      <region v-model="postForm.regionId" @text="addressText = $event" @cityid="postForm.cityRegionId = $event" />
    </el-form-item>
    <el-form-item v-show="postForm.cityRegionId > 0"  label="商业圈：" prop="businessId">
      <business v-model="postForm.businessId" v-model:region-id="postForm.cityRegionId" />
    </el-form-item>
    <el-form-item label="详细地址：" prop="address"> 
      <el-col :span="14">
        <div class="flex-wrap">
          <el-input v-model="postForm.address" placeholder="请输入会场详细地址" />
          <el-input class="input-inner" :value="postForm.longitude ? postForm.longitude + ',' + postForm.latitude : ''" placeholder="会场仓经纬度" disabled />
          <el-button @click="handleSearch">搜索地图</el-button>
        </div>
        <div class="map-wrap" id="mapContainer"></div>
      </el-col>
    </el-form-item>
    <el-form-item label="装修时间：" prop="decorationDate">
      <el-col :span="8">
        <el-date-picker class="ml-gutter" value-format="YYYY-MM-DD" v-model="postForm.decorationDate" type="date" placeholder="请选择装修时间" />
      </el-col>
    </el-form-item>
    <el-form-item label="开业时间：" prop="openingDate">
      <el-col :span="8">
        <el-date-picker class="ml-gutter" value-format="YYYY-MM-DD" v-model="postForm.openingDate" type="date" placeholder="请选择开业时间" />
      </el-col>
    </el-form-item>
    <el-form-item label="停车位数：" prop="parkingCount">
      <el-col :span="14">
        <el-input-number v-model="postForm.parkingCount" :min="0" controls-position="right" />
      </el-col>
    </el-form-item>
    <div class="form-title">图片管理</div>
    <el-form-item label="外观：" prop="exteriorImages">
      <choose-file tips="建议尺寸800x800像素" :limit="12" v-model="postForm.exteriorImages" />
    </el-form-item>
    <el-form-item label="环境：" prop="ambienceImages">
      <choose-file tips="建议尺寸800x800像素" :limit="12" v-model="postForm.ambienceImages" />
    </el-form-item>
    <el-form-item label="大堂：" prop="lobbyImages">
      <choose-file tips="建议尺寸800x800像素" :limit="12" v-model="postForm.lobbyImages" />
    </el-form-item>
    <el-form-item label="餐厅：" prop="diningImages">
      <choose-file tips="建议尺寸800x800像素" :limit="12" v-model="postForm.diningImages" />
    </el-form-item>
    <el-form-item label="娱乐：">
      <choose-file tips="建议尺寸800x800像素" :limit="12" v-model="postForm.playImages" />
    </el-form-item>
    <div class="form-title">简介</div>
    <el-form-item>
      <t-editor v-model="postForm.description" />
    </el-form-item>
    <div class="form-title">配套设施</div>
    <el-form-item label="基础设施：" prop="siteFacilities">
      <facilities :type="PositionType.Site" multiple v-model="postForm.siteFacilities" />
    </el-form-item>
    <el-form-item label="会议室设施：" prop="meetingFacilities">
      <facilities  :type="PositionType.Meeting" multiple v-model="postForm.meetingFacilities" />
    </el-form-item>
    <el-form-item label="客房设施：" prop="guestFacilities">
      <facilities  :type="PositionType.Guest" multiple v-model="postForm.guestFacilities" />
    </el-form-item>
    <el-form-item label="餐厅设施：" prop="diningFacilities">
      <facilities  :type="PositionType.Dining" multiple v-model="postForm.diningFacilities" />
    </el-form-item>
    <div class="form-title">酒店特色</div>
    <el-form-item label="餐厅设施：" prop="diningFacilities">
      <features  :type="PositionType.Site" multiple v-model="postForm.venueFeatures" />
    </el-form-item>
  </el-form>
  <div class="footer">
    <el-button @click="router.push('/site/meeting')">取消</el-button>
    <el-button type="primary" @click="handleSave(postFormRef)">确定</el-button>
  </div>
</template>
<script lang="ts" setup>
import Category from  '@/components/Category.vue'
import Brand from  '@/components/Brand.vue'
import Business from  '@/components/Business.vue'
import Region from  '@/components/Region.vue'
import ChooseFile from '@/components/ChooseFile.vue'
import Facilities from '@/components/Facilities.vue'
import Features from '@/components/Features.vue'
import TEditor from '@/components/TEditor.vue'
import {ref,reactive,onMounted} from 'vue'
import { ElMessage ,ElForm} from 'element-plus'
import {useCommonStore} from '@/stores/common'
import TXMap from '@/assets/js/TXMap'
import QQMapApi from '@/assets/js/qqmapWebService'
import { PositionType } from '@/utils/enum'
import { useRouter,useRoute }  from 'vue-router'
import { SiteSave,GetSiteDetails } from '@/api/site'
import { deepClone } from '@/utils'
const commonStore  = useCommonStore()
const router = useRouter()
const postForm =ref<Venue>({
  id: useRoute().query.id ? Number(useRoute().query.id) : 0,
  name: '',
  tag:'',
  typeId: 0,
  categoryId: undefined,
  brandId: undefined,
  regionId: 0,
  cityRegionId: 0,
  address: '',
  longitude: 0,
  latitude: 0,
  parkingCount: 0,
  decorationDate: undefined,
  openingDate :undefined,
  description:'',
  regionFullIds:'',
  regionFullName:'',
  exteriorImages: [],
  ambienceImages: [],
  lobbyImages: [],
  diningImages: [],
  playImages: [],
  siteFacilities: [],
  meetingFacilities: [],
  guestFacilities: [],
  diningFacilities: [],
  venueFeatures: [],
  businessId: undefined
})
const rules = reactive({
  name: [{ required: true, message: '请输入会场名称', trigger: 'blur' }],
  categoryId: [{ required: true, message: '请选择会场分类', trigger: 'blur' }],
  regionId: [{ required: true, message: '请选择会场地址', trigger: 'blur' }],
  brandId: [{ required: true, message: '请选择品牌', trigger: 'blur' }],
  businessId: [{ required: true, message: '请选择商业圈', trigger: 'blur' }],
  address: [{ required: true, message: '请输入会场详细地址', trigger: 'blur' }],
  decorationDate: [{ required: true, message: '请选择会场装修时间', trigger: 'blur' }],
  openingDate: [{ required: true, message: '请选择会场开业时间', trigger: 'blur' }],
  parkingCount: [{ required: true, message: '请输入停车位', trigger: 'blur' }],
  exteriorImages: [{ type: 'array', required: true, message: '请上传一张外观图片', trigger: 'change' }],
  ambienceImages: [{ type: 'array', required: true, message: '请上传一张环境图片', trigger: 'change' }],
  lobbyImages: [{ type: 'array', required: true, message: '请上传一张大堂图片', trigger: 'change' }],
  diningImages: [{ type: 'array', required: true, message: '请上传一张餐厅图片', trigger: 'change' }],
  playImages: [{ type: 'array', required: true, message: '请上传一张娱乐图片', trigger: 'change' }],
  siteFacilities: [{ type: 'array', required: true, message: '请选择基础设施', trigger: 'change' }],
  meetingFacilities: [{ type: 'array', required: true, message: '请选择会议室设施', trigger: 'change' }],
  guestFacilities: [{ type: 'array', required: true, message: '请选择客房设施', trigger: 'change' }],
  diningFacilities: [{ type: 'array', required: true, message: '请选择餐厅设施', trigger: 'change' }],
})
const addressText = ref<string>('')
const dataMap = reactive({
  map: '',
  markerLayer: '',
  infoWin:  '',
  markers:[]
})
let TMap:any = null
type FormInstance = InstanceType<typeof ElForm>
const postFormRef = ref<FormInstance>()
///加载图片
const init = ():void => {
  TXMap(commonStore.setting.tencentMapKey).then((qq:any) => {
    TMap = qq.maps
    let center = new TMap.LatLng(postForm.value.latitude > 0 ? postForm.value.latitude : 39.916527, postForm.value.longitude > 0 ? postForm.value.longitude : 116.397128)
    dataMap.map = new TMap.Map(document.getElementById('mapContainer'), {
        center: center, 
        zoom: 13, 
        viewMode: '2D'
    })
    ///编辑时候显示标记
    if(postForm.value.id > 0){
      var marker = new qq.maps.Marker({
        position: center
      })
      marker.setMap(dataMap.map)
    }
  
  })
}
window.chooseShopLoc = (res:any) => {
        postForm.value.address = res.getAttribute('address')
        postForm.value.latitude = parseFloat(res.getAttribute('lat'))
        postForm.value.longitude = parseFloat(res.getAttribute('lng'))
}

const mapSearch = () => {
       dataMap.markerLayer = new QQMapApi({
        key: commonStore.setting.tencentMapKey
      })
}

window.QQmap = (res:any) => {
      var pois = res.data
      dataMap.infoWin = new TMap.InfoWindow({
        map:dataMap.map
      })
      let latitude = 0
      let longitude = 0
      for (var i = 0, l = pois.length; i < l; i++) {
         (function (n) { 
             latitude = pois[n].location.lat
             longitude = pois[n].location.lng
             var marker = new TMap.Marker({
                position:  new TMap.LatLng(pois[n].location.lat,pois[n].location.lng),
                map: dataMap.map
            });
             dataMap.markers.push(marker)
             TMap.event.addListener(marker, 'click', () => {
               dataMap.infoWin.open();
               dataMap.infoWin.setContent('<div style="width:200px;padding:10px 0;">' + pois[n].address +
               '<div><input type="button" class="btn-map-import" value="导入经纬度" onclick="chooseShopLoc(this);" address=' +
               pois[n].address + ' lat =' + pois[n].location.lat + '  lng =' + pois[n].location.lng +
               ' /></div></div>')
                dataMap.infoWin.setPosition(new TMap.LatLng(pois[n].location.lat,pois[n].location.lng));
             })
         })(i)
      }
        let center = new TMap.LatLng(latitude, longitude)
        dataMap.map.panTo(center);
  }

  const clearMarkers = () => {
     if (dataMap.markers) {
        for (let i = 0; i < dataMap.markers.length; i++) {
          dataMap.markers[i].setMap(null)
        }
        dataMap.markers.length = 0
      }
   }
  const handleSearch =() => {
    if (!postForm.value.regionId)  
        return ElMessage.error('请选择地址')
    if (!postForm.value.address)  
    return ElMessage.error('请先输入详细地址再搜索')
    dataMap.markerLayer.search({
      keyword: `${addressText.value}${postForm.value.address}`,
      region: addressText.value.split(' ')[1],
      auto_extend: 0
    })
    clearMarkers()
    if (dataMap.infoWin) {
      dataMap.infoWin.close()
    }
  }
  const loadData = ():void => {
    if(postForm.value.id === 0) {
        init()
        mapSearch()
    } else {

      GetSiteDetails(postForm.value.id).then((res:ServiceResponse<VenueEdit>) => {
        if(res.success) {
          if(res.data) {
            postForm.value = deepClone(res.data)
            for(var image in res.data.images)
            {
              switch(image)
              {
                case 'Ambience':postForm.value.ambienceImages = res.data.images[image];break;
                case 'Dining':postForm.value.diningImages = res.data.images[image];break;
                case 'Exterior':postForm.value.exteriorImages = res.data.images[image];break;
                case 'Lobby':postForm.value.lobbyImages = res.data.images[image];break;
                case 'Play':postForm.value.playImages = res.data.images[image];break;
              }
            }
            for(var config in res.data.configs)
            {
              switch(config)
              {
                case 'Dining':postForm.value.diningFacilities = res.data.configs[config];break;
                case 'Guest':postForm.value.guestFacilities = res.data.configs[config];break;
                case 'Meeting':postForm.value.meetingFacilities = res.data.configs[config];break;
                case 'Site':postForm.value.siteFacilities = res.data.configs[config];break;
              }
            }
          }
          console.log('postForm',postForm.value)
          init()
          mapSearch()
        }
      })
    }
  }
  const handleSave = (formEl: FormInstance | undefined): void => {
    if (!formEl) return
    formEl.validate((valid) => {
   
      if(valid) {
        const form:VenueEdit = {
          id: postForm.value.id,
          name: postForm.value.name,
          typeId: postForm.value.typeId,
          categoryId: postForm.value.categoryId,
          brandId: postForm.value.brandId,
          regionId: postForm.value.regionId,
          address: postForm.value.address,
          longitude: postForm.value.longitude,
          latitude: postForm.value.latitude,
          parkingCount: postForm.value.parkingCount,
          decorationDate: postForm.value.decorationDate,
          openingDate: postForm.value.openingDate,
          description: postForm.value.description,
          regionFullIds: postForm.value.regionFullIds,
          regionFullName: postForm.value.regionFullName,
          venueFeatures: postForm.value.venueFeatures,
          businessId: postForm.value.businessId ?? 0,
          cityRegionId: postForm.value.cityRegionId,
          tag: postForm.value.tag,
          images:{3 : postForm.value.exteriorImages, 8:postForm.value.ambienceImages,2:postForm.value.lobbyImages,6:postForm.value.diningImages,7:postForm.value.playImages},
          configs:{1 : postForm.value.siteFacilities, 4:postForm.value.meetingFacilities,5:postForm.value.guestFacilities,6:postForm.value.diningFacilities},
        }
        
        SiteSave(form).then((res:ServiceResponse<any>) => {
          if (res.success) {
             ElMessage.success('操作成功')
             router.push('/site/meeting')
           }
          else 
           return ElMessage.error(res.msg)
        })
      }
    })
  }

onMounted(() => {
  if(!commonStore.setting.tencentMapKey) {
    commonStore.getSetting().then((res:any) => {
      loadData()
    })
  } else {
    loadData()
  }
  
})
</script>
<style lang="scss" scoped>
  @import '@/assets/styles/mixin.scss';
  @import '@/assets/styles/tablePage.scss';
  @import '@/assets/styles/formPage.scss';
  .map-wrap {
  width: 100%;
  height: 360px;
  margin-top: 8px;
  ::v-deep {
    .btn-map-import {
      background: #226bf2;
      border: 0;
      border-radius: 4px;
      color: #fff;
      line-height: 24px;
      font-size: 12px;
      cursor: pointer;
    }
 
  }
}
.flex-wrap {
  display: flex;
  .el-input {
    flex: 1;
  }
  .input-inner {
    max-width: 200px;
  }

}
.ruleForm {
  margin-bottom: 50px;
}
</style>